package org.example.component;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.Arrays;

public class TransactionManagerHandler {
    /**
     * @param joinPoint 连接点（每一个要增强的方法）
     */
    public void begin(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();//被代理的对象，真实对象
        System.out.println("target = " + target);
        Object[] args = joinPoint.getArgs();
        System.out.println("args = " + Arrays.toString(args));
        System.out.println("开启事务");
    }

    public void commit() {
        System.out.println("提交事务");
    }

    public void rollback(Throwable e) {
        e.printStackTrace();
        System.out.println("回滚事务");
    }

    public void close() {
        System.out.println("关闭session");
    }

    //============================环绕通知/增强/advice===============================

    /**
     * @param joinPoint 环绕通知的连接点，环绕通知，需要开发者手动增强，并执行方法
     * @throws Throwable
     */
    public void allInOne(ProceedingJoinPoint joinPoint) throws Throwable {


        try {
            begin(joinPoint);

            //执行连接点方法
            joinPoint.proceed();

            commit();
        } catch (Throwable e) {
            rollback(e);
            throw new RuntimeException(e);
        } finally {
            close();
        }
    }
}